package com.hangzhou.xyj.ui.dialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hangzhou.xyj.R;

/**
 * 数据loading加载对话框控件
 *
 * @author neo.duan
 */
public class LoadingDialog extends Dialog {

    private Context mContext;
    private LayoutInflater inflater;
    private LayoutParams lp;
    private ImageView mIvAnim;
    private TextView mTvLoad;
    private AnimationDrawable mAnimation;
    private ProgressBar mProgressBar;

    public LoadingDialog(Context context) {
        super(context, R.style.MyDialogStyle);

        this.mContext = context;

        inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.layout_loading_dialog, null);
        mIvAnim = (ImageView) layout.findViewById(R.id.iv_loading_anim);
        mProgressBar = (ProgressBar) layout.findViewById(R.id.pb_download_progress_bar);
//        mTvLoad = (TextView) layout.findViewById(R.id.loading_text);
        setContentView(layout);

        // 设置window属性
        lp = getWindow().getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.dimAmount = 0; // 去背景遮盖
        lp.alpha = 1.0f;
        getWindow().setAttributes(lp);

        //设置点击外部不可取消
        setCanceledOnTouchOutside(false);
        setCancelable(false);

        // 通过ImageView对象拿到背景显示的AnimationDrawable
        mAnimation = (AnimationDrawable) mIvAnim.getDrawable();
    }

    public void setLoadText(String content) {
        mTvLoad.setText(content);
        if (mProgressBar.getVisibility() == View.VISIBLE) {
            mProgressBar.setVisibility(View.GONE);
        }
    }

    public void setLoadText(int resid) {
        mTvLoad.setText(resid);
    }

    @Override
    public void show() {
        super.show();
        startAnim();
        if (mProgressBar.getVisibility() == View.VISIBLE) {
            mProgressBar.setVisibility(View.GONE);
        }
    }

    @Override
    public void dismiss() {
        super.dismiss();
        stopAnim();
        mProgressBar.setProgress(0);
    }

    /**
     * 开始动画
     */
    private void startAnim() {
        // 为了防止在onCreate方法中只显示第一帧的解决方案之一
        mIvAnim.post(new Runnable() {
            @Override
            public void run() {
                mAnimation.start();
            }
        });
    }

    private void stopAnim() {
        mAnimation.stop();
    }

    /**
     * 显示进度
     * @param progress
     */
    public void setProgress(int progress) {
        if (mProgressBar.getVisibility() == View.GONE) {
            mProgressBar.setProgress(0);
            mProgressBar.setVisibility(View.VISIBLE);
        }
        mProgressBar.setProgress(progress);
    }
}